const { app, BrowserWindow , ipcMain, shell} = require('electron');
const path = require('path');
const IpcAdapter = require('./ipc/IpcAdapter');
const EVENT = require('./ipc/IpcEvent');
const ConfigService = require('./libs/configService');

//初始化环境变量
//process.env.SERVER_ADDR = "ws://192.168.80.101:3000";
process.env.SERVER_ADDR = "localhost:3000";
process.env.ETAX_ROOT = __dirname;
process.env.ELECTRON_WEB = app.commandLine.getSwitchValue('startweb');
console.log("app index:",process.env.ETAX_ROOT);
console.log("app index:",process.env.ELECTRON_WEB);

//初始化系统对象
const configService = new ConfigService();

const {routers} = new IpcAdapter();

let global_cfg = {
  window : {width:1400,height:900,frame:true},
  islocal : true,
  openDevTools : false,
  hostHistory:[]
}

global_cfg = Object.assign(global_cfg,configService.loadAppConfig());
console.log(global_cfg);
configService.saveAppConfig(global_cfg);

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  let preload = path.join(__dirname, 'preload.js');
  // 创建浏览器窗口.
  let winCfg = global_cfg.window;
  winCfg.webPreferences= {
      preload: preload
  };
  winCfg.backgroundColor = '#2e2c29';
  win = new BrowserWindow(winCfg);
  win.once('ready-to-show', () => {
    win.show()
  })

  if ( process.env.ELECTRON_WEB ) {
    console.log("load from web address.");  
    win.loadURL(process.env.ELECTRON_WEB);
  }else{
    let indexFile = path.join(__dirname, '../public/index.html');
    console.log("load from local file.",indexFile);
    win.loadFile(indexFile);
  }
};

function sysInit(){
  //初始化路由
  for(let routeName in routers) {
      console.log('routeName:', routeName)
      if(routeName === EVENT.COMMON_FULL_SCREEN){
        ipcMain.on(routeName, (e, params) => {
          win && win.maximize()
        })
      }else if(routeName === EVENT.COMMON_EXIT_FULL_SCREEN){
        ipcMain.on(routeName, (e, params) => {
          win && win.unmaximize()
        })
      }else if(routeName === EVENT.COMMON_OPENURL){
        ipcMain.on(routeName, (e, urlPath) => {
          let server = process.env.SERVER_ADDR;
          let config = configService.loadAppConfig();
          server = config.uploadServer;
          if(server && server.search(/:/i) > -1){
             const serverEndPoint = server.split(/:/i);
             let url = "http://" + server + urlPath;
             console.log(url);
             shell.openExternal(url);
          }
        })
      }else{
        ipcMain.on(routeName, (e, params) => {
          console.log('callback params:', routeName, params)
          routers[routeName]({e,arg:params});
        })
      }
  }

  createWindow();
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', sysInit);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
